package com.future.taskdemo.https;

import com.alibaba.fastjson.JSON;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.X509HostnameVerifier;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class Min {

    public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();


    // 要访问的url
    private static final String URL = "https://47.93.119.227:18083/sibService/sibBusiness/services/SIBWebService?wsdl";
    // 证书路径
    private static final String CERT_PATH = "D:\\project\\task-flow\\task-demo\\src\\main\\resources\\tengyang.pfx";
    // 证书密码
    private static final String CERT_PASSWORD = "tengyang";

    private SSLSocketFactory sslFactory = null;

    public static void main(String[] args) {
        Min test = new Min();
        Object requestBody = new Object();
        String result = test.httpsRequest(requestBody);
        System.out.println(result);
    }

    public String httpsRequest(Object requestBody) {
        try {
            Map<String, String> headers = new HashMap<>(2);
            headers.put("Content-Type", "application/json");
            HttpURLConnection connection = doHttpRequest(URL, "POST", requestBody, headers);
            String responseBody = getResponseBodyAsString(connection);
            connection.disconnect();
            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private synchronized SSLSocketFactory getSSLFactory(String certPath, String certPassword) throws Exception {
        if (sslFactory == null) {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager(certPath, certPassword)};
            KeyStore truststore = KeyStore.getInstance("PKCS12");
            truststore.load(new FileInputStream(certPath), certPassword.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(truststore, certPassword.toCharArray());
            sslContext.init(kmf.getKeyManagers(), tm, new java.security.SecureRandom());
            sslFactory = sslContext.getSocketFactory();
        }
        return sslFactory;
    }

    private HttpURLConnection doHttpRequest(String requestUrl, String method, Object req, Map<String, String> header) throws Exception {
        HttpURLConnection conn;
        String body = JSON.toJSONString(req);
        if (method == null || method.length() == 0) {
            method = "GET";
        }
        if ("GET".equals(method) && !body.isEmpty()) {
            requestUrl = requestUrl + "?" + body;
        }

        URL url = new URL(requestUrl);
        conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod(method);

        if (requestUrl.matches("^(https)://.*$")) {
            ((HttpsURLConnection) conn).setSSLSocketFactory(this.getSSLFactory(CERT_PATH, CERT_PASSWORD));
//            ((HttpsURLConnection) conn).setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);
        }

        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }

        if (!body.isEmpty()) {
            if (!"GET".equals(method)) {
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(body);
                wr.close();
            }
        }
        conn.connect();
        return conn;
    }

    private static int getResponseCode(HttpURLConnection connection) throws IOException {
        return connection.getResponseCode();
    }

    private static String getResponseBodyAsString(HttpURLConnection connection) throws Exception {
        BufferedReader reader = null;
        if (connection.getResponseCode() == 200) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        StringBuilder buffer = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    static class MyX509TrustManager implements X509TrustManager {
        private final X509TrustManager sunJSSEX509TrustManager;

        MyX509TrustManager(String certPath, String certPassword) throws Exception {
            // create a "default" JSSE X509TrustManager.
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(new FileInputStream(certPath), certPassword.toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
            tmf.init(ks);
            TrustManager[] tms = tmf.getTrustManagers();

            /*
             * Iterate over the returned trustmanagers, look for an instance of
             * X509TrustManager. If found, use that as our "default" trust manager.
             */
            for (TrustManager tm : tms) {
                if (tm instanceof X509TrustManager) {
                    sunJSSEX509TrustManager = (X509TrustManager) tm;
                    return;
                }
            }
            throw new Exception("Couldn't initialize");
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
            } catch (CertificateException excep) {
            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException excep) {
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return sunJSSEX509TrustManager.getAcceptedIssuers();
        }
    }
}